package com.qianbao.service.shop;

import com.alibaba.fastjson.JSONObject;
import com.qianbao.components.excepion.CommonException;
import com.qianbao.components.excepion.ExceptionEnum;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import org.springframework.stereotype.Service;

@Service
public class ShopService {

    private String serverUrl = "http://gw.api.taobao.com/router/rest";
    private String appKey = "25115608";
    private String appSecret = "17d785856a0d1fd57a30093ed5073e6b";
    private Long adZoneId = 44803700103L;



    public Object tbkDgOptimusMaterial(String pageNo) throws CommonException{
        Object goods = keysSearchGoods("运动健康",pageNo);
        return goods;
    }


    /**
     * 根据关键字搜索宝贝
     * @param keys
     * @return
     */
    public Object keysSearchGoods(String keys,String pageNo) throws CommonException{

        if (keys != null && keys.length() > 0 && pageNo != null && pageNo.length() > 0){

            TaobaoClient client = new DefaultTaobaoClient(serverUrl,appKey,appSecret);
            TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
            req.setAdzoneId(adZoneId);
            req.setPlatform(2L);
            req.setIsOverseas(false);
            req.setIsTmall(false);
            req.setHasCoupon(true);
            req.setNeedFreeShipment(true);
            req.setNeedPrepay(true);
            req.setSort("total_sales_des");

            req.setQ(keys);
            req.setPageNo(Long.valueOf(pageNo));
            req.setPageSize(20L);

            TbkDgMaterialOptionalResponse rsp = null;
            try {
                rsp = client.execute(req);
            } catch (ApiException e) {
                e.printStackTrace();
            }

            String responseJson = rsp.getBody();

            JSONObject jsonObject = JSONObject.parseObject(responseJson);

            JSONObject data = jsonObject.getJSONObject("tbk_dg_material_optional_response");

            if (data != null){
                return data;
            }else {
                throw new CommonException(ExceptionEnum.Shop_list_fail.getCode(),
                        ExceptionEnum.Shop_list_fail.getMessage()
                );
            }

        }else {
            throw new CommonException(ExceptionEnum.Request_Params_Invalid.getCode(),
                    ExceptionEnum.Request_Params_Invalid.getMessage());
        }

    }



}
